
const fs = require('fs')
const zlib = require('zlib')
const path = require('path')
const mimeTypes = {
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.css': 'text/css',
    '.ico': 'image/x-icon',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.gif': 'image/gif',
    '.svg': 'image/svg+xml',
    '.json': 'application/json',
    '.woff': 'font/woff',
    '.woff2': 'font/woff2'
  }
function hasCache (req, res, _path) {
    let stats = fs.statSync(_path)
    let IfModifiedSince = req.headers["if-modified-since"];
    let mtime = stats.mtime
    
    let ext = path.extname(_path)
    !ext && (ext='.html')
    ext && res.setHeader('Content-Type', mimeTypes[ext])
    if(IfModifiedSince && mtime <= new Date(IfModifiedSince).getTime()) {
         res.writeHead(304, 'not modify')
         res.end() 
         return true
     }
     res.setHeader("last-modified", new Date(mtime).getTime())
     let reg = /\.html$/
     res.setHeader('cache-control', reg.test(_path)?'no-cache':`max-age=${1 * 60 * 60 * 24 * 30}`)
     
     return false
 }

function sendReqErrors(res, code, err) {
    code === 404 && res.writeHead(404, 'Not Found')
    res.end()
    console.log(err)
}

module.exports = function (_path, req, res, webPath) {
    try {
        fs.stat(_path, (err, stats) => {
            
            let fileStream = ''
            if (stats) {
                stats.isFile() && (fileStream = fs.createReadStream(_path))
                stats.isDirectory() && fs.existsSync(_path + 'index.html') && (fileStream = fs.createReadStream(_path + 'index.html'))
            }
            if (!stats && (/\.html$/.test(_path) || !/\.[A-Za-z]+$/.test(_path))){
                 _path = path.join(__dirname, webPath, 'dist/', '404.html')
                fs.existsSync(_path) && (fileStream = fs.createReadStream(_path))
            }
            if (fileStream) {
                if (!hasCache(req, res, _path)) {
                    res.setHeader('content-encoding', 'gzip')
                    fileStream.pipe(zlib.createGzip()).pipe(res)
                }
            } else {
                sendReqErrors(res, 404,err)
            }
        })
    } catch (err) {
        sendReqErrors(res, 404,err)
    }
}